// 多图片上传云存储
<template>
  <div>
    <label for="upload">
      选择图片上传
    </label>
    <input
      @change="onChange"
      ref="file"
      type="file"
      multiple
      id="upload"
      style="display: none;"
      accept="image/*tr"
    />
    <p class="tip">提示： 一次可选择多张图片，最多不超过9张</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      client: new OSS({
        region: '',// 云的存储路线选择
        bucket: '',//bucket名称
        accessKeyId: ACCESSKEY.ID,
        accessKeySecret: ACCESSKEY.SECRET
      })
    }
  },
  methods: {
    onChange() {
      //可选链
      const newFiles = this.$refs?.file?.newFiles
      //校验
      if(newFiles.length > 9) {
        alert('最多可以一次选择9张图片')
        return false
      }

      const files = []
      for(const file of newFiles) {
        const size = file.size / 1024 / 1024
        if(size > 1 ) {
          alert('请选择1m以内的图片')
          return false
        }
        files.push(file)
      }
      this.uploadFilesByOss()
    },

    uploadFilesByOss(files) {
      const uploadRequest = []
      for (const file of files) {
        uploadRequest.push(new Promise((resolve, reject) => {
          //上传文件名称
          this.client.put(`${Math.random()}-${file.name}`,file).then((res) => {
            console.log(res);
            resolve()
          }).catch(err => {
            console.log(err);
            reject()
          })
        })
      )

    }
  }
}
</script>

<style lang="scss" scoped></style>
